<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2019 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2019-03-08
 * Time: 17:50
 */

namespace App\Library\Other;


use App\Library\AuthenticatedUser;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

trait ProductNewsManagers
{
    use AuthenticatedUser;

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $id = $request->input('id', 0);
        $data = Arr::only($request->input('news', []), [
            'title',
            'price',
            'quantity',
            'contact',
            'phone',
            'province',
            'city',
            'street',
            'district',
            'image',
            'content'
        ]);

        $images = $request->input('images', []);
        if ($images) {
            $image = Arr::first($images);
            $data['image'] = $image['image'];
        }

        if ($id) {
            $news = $this->user()->saleNews()->find($id);
            if ($news) {
                $news->update($data);
            }
        } else {
            $news = $this->user()->saleNews()->create($data);
            foreach ($images as $image) {
                $news->images()->create($image);
            }
        }

        return ajaxReturn(['news' => $news]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $id = $request->input('id', 0);
        $this->user()->saleNews()->find($id)->delete();
        return ajaxReturn();
    }
}
